package com.cn.algorithm01;

/**
 * https://leetcode-cn.com/problems/balanced-binary-tree
 * 平衡树：左树与右树高度查不超过1时，是平衡树。

 */
public class Code23_BalancedBinaryTree {
    // 创建一个二叉树节点对象
    public static class TreeNode{
        public int val;
        public TreeNode left;
        public TreeNode right;

        public TreeNode(int v) {
            val = v;
        }
    }

    // 是否平衡
    public static boolean isBalanced(TreeNode root) {
        return process(root).isBalanced;
    }

    // 某个局部二叉树的信息
    public static class Info {
        public Boolean isBalanced;
        public int height;

        public Info(Boolean i, int h) {
            isBalanced = i;
            height = h;
        }
    }

    // 对二叉树平衡性以及高度进行递归处理
    public static Info process(TreeNode x) {
        if (x == null) {
            return new Info(true, 0);
        }

        Info leftInfo = process(x.left);
        Info rightInfo = process(x.right);

        Boolean isBalanced = leftInfo.isBalanced && rightInfo.isBalanced
                && Math.abs(leftInfo.height - rightInfo.height) < 2;
        int height = Math.max(leftInfo.height, rightInfo.height) + 1;

        return new Info(isBalanced, height);
    }
}
